//
//  HMChatViewController.m
//  HMWeChat
//
//  Created by apple on 2017/5/11.
//  Copyright © 2017年 itheima. All rights reserved.
//

#import "HMChatViewController.h"


static NSString *sendID = @"send";
static NSString *recvID = @"recv";
static NSString *sendImgID = @"sendImg";
static NSString *recvImgID = @"recvImg";

@interface HMChatViewController ()<UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegate, UITextFieldDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
//查询结果控制器  实时监听消息变化(发出&收到),也需要使用查询结果控制器
@property (nonatomic, strong) NSFetchedResultsController *fetchController;

@property (nonatomic, strong) NSArray <XMPPMessageArchiving_Message_CoreDataObject *> *messages;

@end

@implementation HMChatViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //设置预估行高
    self.tableView.estimatedRowHeight = 200;
    //自动计算行高
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    //执行刷新
    [self refreshData];
}

- (void)refreshData{

   BOOL success = [self.fetchController performFetch:nil];
    if (success) {
        self.messages = self.fetchController.fetchedObjects;
        [self.tableView reloadData];
    }
    //执行滚动
    if (self.messages.count > 0) {
        
        dispatch_async(dispatch_get_main_queue(), ^{ //为了避免没有遍历完数据就执行滚动,将执行滚动的操作添加到主队列的异步任务中,保证在执行到当前任务时,主线程的任务已经全部清空
        
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.messages.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        });
    
    }
}

#pragma mark - 响应事件

- (IBAction)clickSendImgBtn:(id)sender {
    
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate= self;
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    //获取图片
    UIImage *img = info[UIImagePickerControllerOriginalImage];
    //发送文件 接收者的JID必须是fullJID(默认文件只会发给一台设备,需要这台设备的fullJID) 对端如果多台设备在线,应该将数据发送给对端登录的主要设备(最后一次数据交互的设备),主要设备可以通过user表和resource表的多表关系来获取
    //获取该联系人在user表中对应的记录
    XMPPUserCoreDataStorageObject *userCDO = [[XMPPRosterCoreDataStorage sharedInstance] userForJID:self.contactJID xmppStream:[HMXMPPManager sharedManager].xmppStream managedObjectContext:[XMPPRosterCoreDataStorage sharedInstance].mainThreadManagedObjectContext];
    //根据多表关系获取该联系人在resoucre表中的主要设备
    XMPPResourceCoreDataStorageObject *primaryResource = userCDO.primaryResource;
    //从主要设备中获取fullJID
    XMPPJID *fullJID = primaryResource.jid;
    //区分对方是否在线
    if (primaryResource == nil) { //该账号没有一胎设备在线,使用离线文件方式发送
      
        //使用文件中转站 发送离线文件
        XMPPMessage *message = [XMPPMessage messageWithType:@"chat" to:self.contactJID];
        //将上传文件后获取的访问路径设置为消息本体
        [message addBody:@"www.itcast.cn/resource/2017010101.jpg"];
        //设置消息类型
        [message addSubject:[NSString stringWithFormat:@"%lu", HMXMPPMsgTypeOfflineIMG]];
        
        [[HMXMPPManager sharedManager].xmppStream sendElement:message];
        
    } else { //对方在线,使用xmppframework进行文件发送
    
        [[HMXMPPManager sharedManager].xmppOutgoingTF sendData:UIImageJPEGRepresentation(img, 0.1) named:[NSString stringWithFormat:@"%@.jpg", [[HMXMPPManager sharedManager].xmppStream generateUUID]]  toRecipient:fullJID description:[NSString stringWithFormat:@"%lu", HMXMPPMsgTypeIMG] error:nil];
    }

    
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
    /**
     * 为了用户体验,还需要将发送的文件进行以下处理:
     1> 将文件信息(名称,发起者,对端账号)伪装成消息
     2> 保存到数据库
     3> 根据消息类型进行相应的展示
     4> 需要将发送的文件在本地沙盒保存一下
     5> 发送文件时需要同时传递文件类型
     */
    

}



#pragma mark - UITextFieldDelegate

//点击键盘的return事件后调用
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    //封装message节 单聊chat
    XMPPMessage *message = [XMPPMessage messageWithType:@"chat" to:self.contactJID];
    //设置消息内容
    [message addBody:textField.text];
    //发送消息
    [[HMXMPPManager sharedManager].xmppStream sendElement:message];
    //清空内容
    textField.text = nil;
    
    return YES;
}


#pragma mark - NSFetchedResultsControllerDelegate

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller{

    [self refreshData];
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return self.messages.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    UITableViewCell *cell;
    
    XMPPMessageArchiving_Message_CoreDataObject *msgCDO = self.messages[indexPath.row];
    
    //区分不同的类型
    switch ([msgCDO.message.subject intValue]) {
        case HMXMPPMsgTypeTXT: //文本
        {
            //区分发出/接收
            if (msgCDO.isOutgoing) { //发出
                
                cell = [tableView dequeueReusableCellWithIdentifier:sendID forIndexPath:indexPath];
                //显示自己的头像
                UIImageView *imgV = [cell viewWithTag:1001];
                imgV.image = [UIImage imageWithData:[HMXMPPManager sharedManager].xmppvCard.myvCardTemp.photo];
                
            }else { //接收
                
                cell = [tableView dequeueReusableCellWithIdentifier:recvID forIndexPath:indexPath];
                
                //显示联系人的头像
                UIImageView *imgV = [cell viewWithTag:1001];
                imgV.image = [UIImage imageWithData:[[HMXMPPManager sharedManager].xmppAvatar photoDataForJID:self.contactJID]];
                
            }
            //设置数据
            UILabel *contentLabel = [cell viewWithTag:1002];
            contentLabel.text = msgCDO.message.body;
        }
            break;
            
        case HMXMPPMsgTypeIMG: //图片
        {
            //区分发出/接收
            if (msgCDO.isOutgoing) { //发出
                
                cell = [tableView dequeueReusableCellWithIdentifier:sendImgID forIndexPath:indexPath];
                //显示自己的头像
                UIImageView *imgV = [cell viewWithTag:1001];
                imgV.image = [UIImage imageWithData:[HMXMPPManager sharedManager].xmppvCard.myvCardTemp.photo];
                
            }else { //接收
                
                cell = [tableView dequeueReusableCellWithIdentifier:recvImgID forIndexPath:indexPath];
                
                //显示联系人的头像
                UIImageView *imgV = [cell viewWithTag:1001];
                imgV.image = [UIImage imageWithData:[[HMXMPPManager sharedManager].xmppAvatar photoDataForJID:self.contactJID]];
                
            }
            //设置数据
            UIImageView *contentImgV = [cell viewWithTag:1002];
            NSString *path = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:msgCDO.message.body];
            
            contentImgV.image = [UIImage imageWithContentsOfFile:path];
        }
            break;
            
        default:
            break;
    }
    
   
    
    return cell;
}


#pragma mark - 懒加载

- (NSFetchedResultsController *)fetchController{
    
    if (_fetchController == nil) {
        
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"XMPPMessageArchiving_Message_CoreDataObject" inManagedObjectContext:[XMPPMessageArchivingCoreDataStorage sharedInstance].mainThreadManagedObjectContext];
        [fetchRequest setEntity:entity];
        //设置过滤条件  消息必须是当前联系人的
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"bareJidStr = %@", self.contactJID.bare];
        [fetchRequest setPredicate:predicate];
        // 设置排序   时间升序
        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"timestamp" ascending:YES];
        [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
        
        _fetchController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:[XMPPMessageArchivingCoreDataStorage sharedInstance].mainThreadManagedObjectContext sectionNameKeyPath:nil cacheName:nil];
        
        _fetchController.delegate = self;
    }
    return _fetchController;
}

@end
